{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "XYYDvoskkE61"
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "from tensorflow.keras.preprocessing.text import Tokenizer\n",
    "from tensorflow.keras.preprocessing.sequence import pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "0eJSTTYnkJQd"
   },
   "outputs": [],
   "source": [
    "vocab_size = 10000\n",
    "embedding_dim = 16\n",
    "max_length = 100\n",
    "trunc_type='post'\n",
    "padding_type='post'\n",
    "oov_tok = \"<OOV>\"\n",
    "training_size = 20000\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "BQVuQrZNkPn9"
   },
   "outputs": [],
   "source": [
    "# !wget --no-check-certificate \\\n",
    "#     https://storage.googleapis.com/laurencemoroney-blog.appspot.com/sarcasm.json \\\n",
    "#     -O /tmp/sarcasm.json\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "oaLaaqhNkUPd"
   },
   "outputs": [],
   "source": [
    "with open(\"../../tensorflow_datasets/sarcasm.json\", 'r') as f:\n",
    "    datastore = json.load(f)\n",
    "\n",
    "sentences = []\n",
    "labels = []\n",
    "\n",
    "for item in datastore:\n",
    "    sentences.append(item['headline'])\n",
    "    labels.append(item['is_sarcastic'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "S1sD-7v0kYWk"
   },
   "outputs": [],
   "source": [
    "training_sentences = sentences[0:training_size]\n",
    "testing_sentences = sentences[training_size:]\n",
    "training_labels = labels[0:training_size]\n",
    "testing_labels = labels[training_size:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "3u8UB0MCkZ5N"
   },
   "outputs": [],
   "source": [
    "tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)\n",
    "tokenizer.fit_on_texts(training_sentences)\n",
    "\n",
    "word_index = tokenizer.word_index\n",
    "\n",
    "training_sequences = tokenizer.texts_to_sequences(training_sentences)\n",
    "training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\n",
    "\n",
    "testing_sequences = tokenizer.texts_to_sequences(testing_sentences)\n",
    "testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "FufaT4vlkiDE"
   },
   "outputs": [],
   "source": [
    "model = tf.keras.Sequential([\n",
    "    tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\n",
    "    tf.keras.layers.GlobalAveragePooling1D(),\n",
    "    tf.keras.layers.Dense(24, activation='relu'),\n",
    "    tf.keras.layers.Dense(1, activation='sigmoid')\n",
    "])\n",
    "model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "XfDt1hmYkiys"
   },
   "outputs": [],
   "source": [
    "model.summary()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "2DTKQFf1kkyc"
   },
   "outputs": [],
   "source": [
    "num_epochs = 30\n",
    "training_padded = np.array(training_padded)\n",
    "training_labels = np.array(training_labels)\n",
    "testing_padded = np.array(testing_padded)\n",
    "testing_labels = np.array(testing_labels)\n",
    "history = model.fit(training_padded, training_labels, epochs=num_epochs, validation_data=(testing_padded, testing_labels), verbose=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "2HYfBKXjkmU8"
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "def plot_graphs(history, string):\n",
    "  plt.plot(history.history[string])\n",
    "  plt.plot(history.history['val_'+string])\n",
    "  plt.xlabel(\"Epochs\")\n",
    "  plt.ylabel(string)\n",
    "  plt.legend([string, 'val_'+string])\n",
    "  plt.show()\n",
    "  \n",
    "plot_graphs(history, \"accuracy\")\n",
    "plot_graphs(history, \"loss\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "7SBdAZAenvzL"
   },
   "outputs": [],
   "source": [
    "reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n",
    "\n",
    "def decode_sentence(text):\n",
    "    return ' '.join([reverse_word_index.get(i, '?') for i in text])\n",
    "\n",
    "print(decode_sentence(training_padded[0]))\n",
    "print(training_sentences[2])\n",
    "print(labels[2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "c9MqihtEkzQ9"
   },
   "outputs": [],
   "source": [
    "e = model.layers[0]\n",
    "weights = e.get_weights()[0]\n",
    "print(weights.shape) # shape: (vocab_size, embedding_dim)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LoBXVffknldU"
   },
   "outputs": [],
   "source": [
    "import io\n",
    "\n",
    "out_v = io.open('vecs.tsv', 'w', encoding='utf-8')\n",
    "out_m = io.open('meta.tsv', 'w', encoding='utf-8')\n",
    "for word_num in range(1, vocab_size):\n",
    "  word = reverse_word_index[word_num]\n",
    "  embeddings = weights[word_num]\n",
    "  out_m.write(word + \"\\n\")\n",
    "  out_v.write('\\t'.join([str(x) for x in embeddings]) + \"\\n\")\n",
    "out_v.close()\n",
    "out_m.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "U4eZ5HtVnnEE"
   },
   "outputs": [],
   "source": [
    "# try:\n",
    "#   from google.colab import files\n",
    "# except ImportError:\n",
    "#   pass\n",
    "# else:\n",
    "#   files.download('vecs.tsv')\n",
    "#   files.download('meta.tsv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "cG8-ArY-qDcz"
   },
   "outputs": [],
   "source": [
    "sentence = [\"granny starting to fear spiders in the garden might be real\", \"game of thrones season finale showing this sunday night\"]\n",
    "sequences = tokenizer.texts_to_sequences(sentence)\n",
    "padded = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\n",
    "print(model.predict(padded))"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "Course 3 - Week 2 - Lesson 2.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
